package weibo4andriod.andriodexamples;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import weibo4andriod.http.RequestToken;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import android.view.LayoutInflater; 

public class AndriodExample extends Activity {
	/** Called when the activity is first created. */
	int[] imgPath = {R.drawable.a, R.drawable.b};
	Bitmap bmpResult;
	private final String PREFERENCES_NAME="oauth";
	private final CharSequence[] items = {"发送短信", "发送sina微博", "QQ微博"}; 
	private String token;
	private String secret;
	private ProgressDialog m_Dialog;
	private EditText UserNameText, PasswordText;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
    	System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
	}
	
	// 生成结果
    public void onMakeClick( View v )
    {
    	SharedPreferences preferences = getSharedPreferences(PREFERENCES_NAME, Activity.MODE_PRIVATE);
        token = preferences.getString("token", "");
        secret = preferences.getString("secret", "");
        OAuthConstant.getInstance().setToken(token);
        OAuthConstant.getInstance().setTokenSecret(secret);
        EditText nameText = (EditText)findViewById(R.id.editText1);
         Bitmap bmp = makeBmpResult(nameText.getText().toString());
        ImageView iView = (ImageView)findViewById(R.id.imageView1);
        bmpResult = mergeBitmapText(bmp, nameText.getText().toString());
        iView.setImageBitmap(bmpResult);
        //iView.setUserName(nameText.getText().toString()); 
        //iView.setImageResource(makeBmpResult(nameText.getText().toString()));
        //iView.setDrawingCacheEnabled(true);
        //bmpResult = iView.getDrawingCache();
    }
    
    public void onSelectClick(View v)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(AndriodExample.this);
    	builder.setTitle("选择发送方式").setItems(items, new DialogInterface.OnClickListener() {
    	    public void onClick(DialogInterface dialog, int item) 
    	    {
    	    	switch(item)
    	    	{
    	    		case 0:
    	    			Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bmpResult, null,null));
    	    			Intent sendIntent = new Intent(Intent.ACTION_SEND);  
    	    			sendIntent.putExtra("sms_body", "some text");  
    	    			sendIntent.putExtra(Intent.EXTRA_STREAM, uri); 
    	    			sendIntent.setType("image/png");  
    	    			startActivity(sendIntent); 
    	    			break;
	    	    	case 1:
	    	    	case 2:
//	    	          if ("" == token)
//	    	          {
	    	        	  LayoutInflater factory = LayoutInflater.from(AndriodExample.this);  
	    	        	  final View DialogView = factory.inflate(R.layout.login, null);  
	    	        	  new AlertDialog.Builder(AndriodExample.this).setTitle(getResources().getString(R.string.login_title))
	    	        	  .setView(DialogView).
	    	        	  setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
	    	        	  {  
	    	        		  public void onClick(DialogInterface dialog, int which) 
	    	        		  {  
	    	        			  m_Dialog = ProgressDialog.show(AndriodExample.this, getResources().getString(R.string.pls_waiting), getResources().getString(R.string.logining),true);  
	    	        			  new Thread(){  
	    	        				  public void run()
	    	        				  {  
	    	        					  try
	    	        					  {
	    	        						  Bundle bundle = new Bundle();//该类用作携带数据 
	    	        						  byte[] imgData = Bitmap2Bytes(bmpResult);
	    	        						  bundle.putByteArray("imgData", imgData);
	    	        						  UserNameText = (EditText)DialogView.findViewById(R.id.username);
	    	        						  PasswordText = (EditText)DialogView.findViewById(R.id.password);
	    	        						  String username = UserNameText.getText().toString();
	    	        						  String password = PasswordText.getText().toString();
	    	        						  openAuthPage(bundle, username, password);
	    	        					  }
	    	        					  catch(Exception ex)
	    	        					  {  
	    	        						  ex.printStackTrace();  
	    	        					  }
	    	        					  finally
	    	        					  {  
	    	        						  m_Dialog.dismiss();  
	    	        					  }  
	    	        				  }  
	    	        			  }.start();  
	    	        		  }  
	    	        	  }).setNegativeButton(getResources().getString(R.string.no), new DialogInterface.OnClickListener(){      
		                    @Override  
		                    	public void onClick(DialogInterface dialog, int which) {  
		                    		m_Dialog.dismiss();  
		                    	}  
	    	        	  })  
	    	        	  .create().show();
//	    	          	}
//		    	        else{
//		    	        	Bundle bundle = new Bundle();//该类用作携带数据 
//                        	byte[] imgData = Bitmap2Bytes(bmpResult);
//        	    	        bundle.putByteArray("imgData", imgData);
//        	    	        Intent intent = new Intent(AndriodExample.this, OAuthActivity.class); 
//        	    	        intent.putExtras(bundle);//附带上额外的数据
//        	    	        startActivity(intent);
//        	    	        m_Dialog.dismiss();  
//		    	        }
		                break;
	                default:
	                	Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
	                	break;
    	    	}
    	    }
    	}).setNegativeButton("取消", new DialogInterface.OnClickListener() {  
            @Override  
            public void onClick(DialogInterface dialog, int which) {  
                dialog.dismiss(); //关闭alertDialog  
            }  
        }).show(); // title  
    }
    
    /**
     * 图片合成
     * @param bitmap
     * @return
     */
   private Bitmap mergeBitmapText( Bitmap src, String text) {
        if( src == null ) {
            return null;
        }
        int w = src.getWidth();
        int h = src.getHeight();
        //create the new blank bitmap
        Bitmap newb = Bitmap.createBitmap(w, h, src.getConfig());//创建一个新的和SRC长度宽度一样的位图
        Canvas cv = new Canvas(newb);
        cv.drawBitmap( src, 0, 0, null );
        Paint paint = new Paint();
    	{ 
    		paint.setAntiAlias(true);
    		paint.setTextSize(30);
    	    paint.setColor(Color.DKGRAY); 
    	}; 
        cv.drawText(text, 107, 47, paint);
        //save all clip   
        cv.save( Canvas.ALL_SAVE_FLAG );//保存
        //store
        cv.restore();//存储
        return newb;
   }
    
    
    // 发送到微博
    public void onSendClick( View v ){
//    	Bundle bundle = new Bundle();//该类用作携带数据 
//        byte[] imgData = Bitmap2Bytes(bmpResult);
//        bundle.putByteArray("imgData", imgData);
//        if ("" == token)
//        	openAuthPage(bundle);
//        else{
//        	 Intent intent = new Intent(AndriodExample.this, OAuthActivity.class); 
//        	 intent.putExtras(bundle);//附带上额外的数据
//        	 startActivity(intent);
//        }
    }
	
	// 打开授权页面
	private void openAuthPage(Bundle bundle, String username, String password){
    	Weibo weibo = OAuthConstant.getInstance().getWeibo();
    	RequestToken requestToken;
		try {
			requestToken =weibo.getOAuthRequestToken("weibo4andriod://OAuthActivity");
			OAuthConstant.getInstance().setRequestToken(requestToken);
			String verifier = httpGetVerifier("http://api.t.sina.com.cn/oauth/authorize?oauth_token="+requestToken.getToken()+"&oauth_callback=json&userId="+username+"&passwd="+password);
			Intent intent = new Intent(AndriodExample.this, OAuthActivity.class);
			intent.putExtras(bundle);
			intent.putExtra("verifier", verifier);
			startActivity(intent);
		} catch (WeiboException e) {
			e.printStackTrace();
		}
	}
	
	private String httpGetVerifier(String httpUrl){
		HttpGet request = new HttpGet(httpUrl);  
		DefaultHttpClient httpClient = new DefaultHttpClient ();  
        try {
            HttpResponse response = httpClient.execute(request);  
            if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){  
                String result = EntityUtils.toString(response.getEntity());
                weibo4andriod.org.json.JSONObject j = new weibo4andriod.org.json.JSONObject(result);
                return (String)j.get("oauth_verifier");
            }else{
            	System.out.println("error");
            	return null;
        }   
        } catch (ClientProtocolException e) {  
            e.printStackTrace();      
        } catch( weibo4andriod.org.json.JSONException e){
        	e.printStackTrace();
        } catch (IOException e) {  
            e.printStackTrace(); 
        }
		return null;
	}
	
	
	// 
	public Bitmap makeBmpResult(String name){
      	int hashcode = name.hashCode();
      	int index = (hashcode & 0x7FFFFFFF) % imgPath.length; 
      	return BitmapFactory.decodeResource(getResources(), imgPath[index]);
  	}
	
	private byte[] Bitmap2Bytes(Bitmap bm){  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();    
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);    
        return baos.toByteArray();  
       }  

}